﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Crawler_v1.service.impl;
using Newtonsoft.Json;
using Crawler_v1.bean;
using Crawler_v1.spider;
using Crawler_v1.spider.entity;
using MetroFramework.Forms;
using Crawler_v1.entity;
using Crawler_v1.utils;
using MetroFramework;


namespace Crawler_v1.ui
{
    public partial class MainForm : MetroForm, ISpiderListener
    {
        public MainForm()
        {
            InitializeComponent();
        }

        ThreadSpider spider;

        /// <summary>
        /// 窗口加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void main_Load(object sender, EventArgs e)
        {

            /* 初始化栏目数据 */
            var json = FileUtil.readText("columns2.json");
            List<Column> columns = JsonConvert.DeserializeObject<List<Column>>(json);


            this.listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度

            for (int i = 0; i < columns.Count; i++)   //添加10行数据
            {
                Column column = columns[i];

                ListViewItem lvi = new ListViewItem();

                lvi.Text = column.parent;

                lvi.SubItems.Add(column.text);//第2列
                lvi.SubItems.Add(column.href);//第3列
                //lvi.SubItems.Add("第3列,第" + i + "行");

                this.listView1.Items.Add(lvi);
            }

            this.listView1.EndUpdate();  //结束数据处理，UI界面一次性绘制。


            //grid view动态改变宽度
            int totalWidth = dataGrid.Width;
            int size = dataGrid.Columns.Count;
            //int[] weight=new int[dataGrid.Columns.Count];
            for (int i = 0; i < size; i++)
            {
                dataGrid.Columns[i].Width = totalWidth / size;
            }

            initDataGrid();
        }

        #region 按钮事件

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {

                try
                {
                    var item = listView1.SelectedItems[0];

                    //初始化pipeline
                    SqlitePipeLine pipeline = new SqlitePipeLine();
                    int crawler_size = Convert.ToInt32(crawlerSize.Text);
                    pipeline.CrawlerSize = crawler_size;

                    //初始化schedule
                    string parent = item.SubItems[0].Text;
                    string name = item.SubItems[1].Text;
                    string href = item.SubItems[2].Text;
                    Schedule schedule = new Schedule(href, name, parent);

                    int column_page = Convert.ToInt32(columnPage.Text);
                    schedule.Page = column_page;//设置页码

                    //初始化spider
                    spider = new ThreadSpider(schedule, pipeline);
                    spider.SpiderListener = this;
                    spider.start();

                    //ui控制
                    btnStart.Enabled = false;

                    btnPause.Enabled = true;
                    btnPause.Text = "暂停";
                    btnStop.Enabled = true;

                    showProgress();

                    dataGrid.Rows.Clear();
                    metroTextBox1.Clear();

                    columnPage.Enabled = false;
                    crawlerSize.Enabled = false;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            else
            {

                MessageBox.Show("请选择栏目");
            }


        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (spider.isStarted())
            {
                spider.stop();
                hideProgress();
                btnPause.Text = "继续";
            }
            else
            {
                spider.start();
                showProgress();
                btnPause.Text = "暂停";
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            spider.stop();
            spider = null;

            btnStart.Enabled = true;
            btnPause.Enabled = false;
            btnStop.Enabled = false;

            hideProgress();

            columnPage.Enabled = true;
            crawlerSize.Enabled = true;
        }

        private void showProgress()
        {
            progressSpinner1.Visible = true;
            progressText1.Visible = true;
        }

        private void hideProgress()
        {
            progressSpinner1.Visible = false;
            progressText1.Visible = false;
        }

        /// <summary>
        /// 打开官网
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void metroLink1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://fec.mofcom.gov.cn/article/fwydyl/tjsj/");  //利用Process.Start来打开
        }

        #endregion


        public void printLog(string msg)
        {
            this.BeginInvoke(new Action<string>((str) =>
            {

                this.metroTextBox1.AppendText(System.Environment.NewLine + str);

            }), msg);
        }

        /* 实现spider的接口 */

        void ISpiderListener.onFinishOne(Page page)
        {

            int threadCount = 0;
            if (spider != null)
            {
                threadCount = spider.getRunningCount();
            }


            //printLog("url解析完成:" + page.Url);
            Article article2 = page.Data as Article;
            printLog("文章【" + article2.title + "】处理完成");

            this.BeginInvoke(new Action<Page, int>((myPage, count) =>
            {

                //datagridview

                Article article = page.Data as Article;
                if (article != null)
                {
                    int rowIndex = this.dataGrid.Rows.Add();
                    int curIndex = rowIndex;

                    List<string> datas = new List<string>();
                    datas.Add(article.column);
                    datas.Add(article.title);
                    datas.Add(Convert.ToString(article.date));
                    datas.Add(page.Url);

                    for (int i = 0; i < datas.Count; i++)
                    {
                        this.dataGrid.Rows[curIndex].Cells[i].Value = datas[i];
                    }

                }

                progressText1.Text = "采集栏目" + article.column + "中，当前" + count + "个线程在运行";

            }), page, threadCount);


        }

        void ISpiderListener.onFinishAll()
        {

            printLog("全部解析完成");

            this.BeginInvoke(new Action(() =>
            {
                btnStop_Click(null, null);
            }));

        }

        void ISpiderListener.onError(Exception ex)
        {
            printLog(ex.Message);
        }


        void ISpiderListener.onMsg(string msg)
        {
            printLog(msg);
        }


        MetroColorStyle[] styles = new MetroColorStyle[]{
                MetroColorStyle.Default,MetroColorStyle.Black,MetroColorStyle.Blue,MetroColorStyle.Brown,
                MetroColorStyle.Green,MetroColorStyle.Lime,MetroColorStyle.Magenta,MetroColorStyle.Orange,
                MetroColorStyle.Pink,MetroColorStyle.Purple,MetroColorStyle.Red,MetroColorStyle.Silver,
                MetroColorStyle.Teal,MetroColorStyle.White,MetroColorStyle.Yellow
            };
        int currentStyleIndex = 0;
        /// <summary>
        /// 切换样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSwitchStyle_Click(object sender, EventArgs e)
        {
            currentStyleIndex++;
            if (currentStyleIndex >= styles.Length)
            {
                currentStyleIndex = 0;
            }
            metroStyleManager1.Style = styles[currentStyleIndex];
        }

        MetroThemeStyle[] themes = new MetroThemeStyle[] { MetroThemeStyle.Default, MetroThemeStyle.Dark, MetroThemeStyle.Light };
        int currentThemeIndex = 0;
        /// <summary>
        /// 切换主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void metroThemeToggle_CheckedChanged(object sender, EventArgs e)
        {
            currentThemeIndex++;
            if (currentThemeIndex >= themes.Length)
            {
                currentThemeIndex = 0;
            }
            metroStyleManager1.Theme = themes[currentThemeIndex];
        }

    }
}
